<template>
  <div class="img_info">
    <div>
      <el-button
        class="download_btn"
        v-if="showBtn('下载精修图片')"
        size="mini"
        type="primary"
        :loading="downloadImgLoading"
        @click="handleDownloadImg"
        >一键下载精修图片</el-button
      >
      <p>商品准入操作人：{{operationInfo.createOperUserName}} {{operationInfo.createOperTime}}</p>
      <p>最后一次修改人：{{operationInfo.operUserName}} {{operationInfo.operTime}}</p>
    </div>
    <Card dis-hover>
      <Form :label-width="180">
        <FormItem label="商品主图片（未精修）">
          <Row
            style="padding-top: 10px"
          >
            <Upload
              class="ivu-mr qw-disflex"
              :defaultList="goodsAvaterUntruing"
              :mr="16"
              readOnly
            ></Upload>
          </Row>
        </FormItem>
        <FormItem label="商品主图片（精修）">
          <Row
            style="padding-top: 10px"
          >
            <Upload
              class="ivu-mr qw-disflex truing_img"
              :defaultList="goodsAvaterTruing"
              :mr="16"
              readOnly
            ></Upload>
          </Row>
        </FormItem>
        <FormItem label="商品多角度图（未精修）">
          <Row
            style="padding-top: 10px"
          >
            <Upload
              class="ivu-mr qw-disflex"
              :defaultList="goodsMultiangleUntruing"
              :mr="16"
              readOnly
            ></Upload>
          </Row>
        </FormItem>
        <FormItem label="商品多角度图（精修）">
          <Row
            style="padding-top: 10px"
          >
            <Upload
              class="ivu-mr qw-disflex truing_img"
              :defaultList="goodsMultiangleTruing"
              :mr="16"
              readOnly
            ></Upload>
          </Row>
        </FormItem>
      </Form>
    </Card>
    <Card dis-hover title="SKU 图片">
      <Table
        style="margin-bottom: 16px"
        border
        ref="selection"
        :columns="columns4"
        :data="skuList"
      ></Table>
      <Form :label-width="180">
        <FormItem
          v-for="(item, index) in tableSelect"
          :key="index"
          :label="item.skuNo + '商品图片'"
        >
          <Upload
            readOnly
            class="ivu-mr qw-disflex truing_img"
            :defaultList="item.img"
            :mr="16"
          >
          </Upload>
        </FormItem>
      </Form>
    </Card>
    <Card  style="height: 900px" dis-hover>
      <Form style="padding-top: 16px">
        <FormItem label="详情信息">
          <div>
            <i-quill
              class="truing_img"
              v-model="pcDetail"
            ></i-quill>
          </div>
        </FormItem>
      </Form>
    </Card>
  </div>
</template>

<script>
import { ApiRequest, ApiRequestExportTable } from '@api/basePage';
import iQuill from '@/components/quill'; // 编辑器组件
import Upload from '@/components/common/upload'; // 上传组件
import photo from './component/photoGallery'; // 图片库选择
import util from '@/libs/util';
import { uniqueImageKeyData } from '@/assets/js/utils';
import { mapGetters } from 'vuex';

export default {
  name: 'tuwenjieshao',
  components: {
    iQuill,
    Upload,
    photo,
  },
  data () {
    return {
      spuNo: '',
      downloadImgLoading: false,
      productUuid: '', // 商品uuid
      animal: '1',
      videoKey: [], // 供应商视频
      saleVideoKey: [], // 销售用视频
      vediolist: [],
      button1: '本地上传',
      button2: '本地上传',
      button3: '本地上传',
      button4: '本地上传',
      tableSelect: [],
      goodsAvaterTruing: [], // 商品主图片-精修
      goodsAvaterUntruing: [], // 商品主图片-未精修
      goodsMultiangleTruing: [], // 商品多角度-精修
      goodsMultiangleUntruing: [], // 商品多角度-未精修
      skuImageList: [], // sku图片
      phoneDetail: '', // 移动端详情
      pcDetail: '', // PC端详情
      isNew: '1', // 1 新增  2 修改
      recordNo: '', // 单据号
      columns4: [
        {
          title: 'SKU编码',
          key: 'skuNo',
          align: 'center',
          width: 150
        },
        {
          title: 'SKU名称',
          key: 'skuName',
          align: 'center',
        },
        {
          title: '规格',
          key: 'specDetailStr',
          align: 'center',
        }
      ],
      skuList: [],
      skuList11: [],
      operationInfo: {
        createOperUserName: '', // 商品准入操作人
        createOperTime: '', // 商品准入时间
        operUserName: '', // 最后修改人
        operTime: '' // 最后修改时间
      }
    };
  },
  computed: {
    ...mapGetters('permissions/systemBtns', ['showBtn'])
  },
  created () {
    const { spuNo } = this.$route.query;
    this.spuNo = spuNo;
    this.productUuid = util.Pub.getStorageSync('productUuidDetail');
  },
  methods: {
    getPageData () {
      if (this.goodsAvaterUntruing.length > 0 || this.goodsAvaterTruing.length > 0 || this.goodsMultiangleTruing.length > 0 || this.goodsMultiangleUntruing.length > 0) {
        return;
      }
      // 初始回显接口
      let that = this;
      let data = {
        productUuid: this.productUuid
      };
      ApiRequest(
        '/sysback/productinfo/getPicInfoByProductUuid',
        'get',
        data,
        true
      ).then((res) => {
        if (res.retStatus === '1') {
          let resData = res.retData;
          const {
            createOperUserName,
            createOperTime,
            operUserName,
            operTime
          } = resData;
          this.operationInfo = {
            createOperUserName,
            createOperTime,
            operUserName,
            operTime
          }
          if (resData.mainImage !== null) {
            this.isNew = '2';
          }
          // 主图 未精修
          if (resData.mainImage !== null) {
            // 用于判断是否为编辑
            let mainimg = {
              url: resData.mainImage.mainImageKey
            };
            this.goodsAvaterUntruing.push(mainimg);
            // 主图 精修
            let truingimg = {
              url: resData.mainImage.trimmingKey
            };
            this.goodsAvaterTruing.push(truingimg);
          }
          if (resData.multiImageList !== null) {
            // 多角度图
            let imageList = uniqueImageKeyData(resData.multiImageList);
            let sortImageList = _.sortBy(imageList, item => { // 图片排序
              return item.position;
            })
            sortImageList.forEach(function (item, index) {
              if (item.trimming === '1') {
                let imgobj = {
                  url: item.basicImageKey
                };
                that.goodsMultiangleTruing.push(imgobj);
              } else {
                let imgobj = {
                  url: item.basicImageKey
                };
                that.goodsMultiangleUntruing.push(imgobj);
              }
            });
          }

          if (resData.description !== null) {
            // 图文描述
            this.animal = resData.description.currency;
            this.pcDetail = resData.description.description;
            this.phoneDetail = resData.description.appdescrition;
          }
          let skuImageList =
            resData.skuImageList && resData.skuImageList.length > 0
              ? resData.skuImageList
              : [];
          // sku图片
          skuImageList.forEach(function (skuitem, skuindex) {
            let select = {
              skuNo: skuitem.skuNo,
              img: [],
              button: '本地上传'
            };
            if (resData.skuImageUpdateList !== null) {
              let imageList = uniqueImageKeyData(resData.skuImageUpdateList);
              imageList.forEach(function (item, index) {
                if (skuitem.skuNo === item.skuNo) {
                  skuitem._checked = true;
                  select.skuNo = skuitem.skuNo
                  select.img.push({
                    url: item.basicImageKey
                  });
                }
              });
            }
            if (select.img.length > 0) {
              that.tableSelect.push(select);
              skuitem.img = select.img;
            }
          });
          // 供应商视频
          this.videoKey = resData.mainImage.videoKey;
          // 销售用视频
          this.saleVideoKey = resData.mainImage.saleVideoKey;
          /* that.skuList = that.skuList11; */
          this.getSku(resData.skuImageList)
        }
      });
    },

    // 获取sku列表
    getSku (skuImageList) {
      let that = this;
      let data = {};
      ApiRequest(
        '/sysback/sku/list/getSkuByProduct?productUuid=' +
          this.productUuid,
        'post',
        data
      ).then((res) => {
        if (res.retStatus == '1') {
          let sku = res.retData;
          sku.forEach(function (item, index) {
            let button = '本地上传';
            let img = [];
            item.button = button;
            item.img = img;
          });
          that.skuList11 = sku;
          // sku图片
          that.skuList11.forEach(function (skuitem, skuindex) {
            let select = {
              skuNo: skuitem.skuNo,
              img: [],
              button: '本地上传'
            };
            if (skuImageList !== null && skuImageList.length > 0) {
              skuImageList.forEach(function (item, index) {
                if (skuitem.skuNo === item.skuNo) {
                  skuitem._checked = true;
                  select.skuNo = skuitem.skuNo;
                  select.img.push({
                    url: item.basicImageKey
                  });
                }
              });
            }
            if (select.img.length > 0) {
              that.tableSelect.push(select);
              skuitem.img = select.img;
            }
          });
          that.skuList = that.skuList11;
        }
      });
    },

    // 图片库 点击 确认 返回的图片列表
    getChildPhoto (data, i, si) {
      switch (i) {
        case '1':
          // 商品头未精修
          this.goodsAvaterUntruing = data;
          break;
        case '2':
          // 商品头精修
          this.goodsAvaterTruing = data;
          break;
        case '3':
          // 商品多角度未精修
          this.goodsMultiangleUntruing = data;
          break;
        case '4':
          // 商品多角度精修
          this.goodsMultiangleTruing = data;
          break;
        case 's':
          this.tableSelect[si].img = data;
      }
    },
    // 下载图片
    handleDownloadImg () {
      let imgDomList = document.querySelectorAll('.truing_img img');
      let urls = [];
      for (let i = 0; i <= imgDomList.length; i++) {
        if (
          imgDomList[i] &&
          imgDomList[i].src &&
          !urls.includes(imgDomList[i].src)
        ) {
          urls.push(imgDomList[i].src);
        }
      }
      this.downloadImgLoading = true;
      ApiRequestExportTable(
        `/sysback/fileserver/getPicZip`,
        'post',
        { spuNo: this.spuNo, urls },
        false
      )
        .then((res) => {
          const blob = new Blob([res], {
            type: 'application/octet-stream'
          });
          var link = document.createElement('a');
          link.href = window.URL.createObjectURL(blob);
          link.download = '精修图片.zip';
          link.click();
          window.URL.revokeObjectURL(blob);
          this.downloadImgLoading = false;
        })
        .catch(() => {
          this.downloadImgLoading = false;
          this.$message.error('下载失败');
        });
    }
  }
};
</script>

<style lang="less" scoped>
.img_info {
  .download_btn {
    margin: 10px 0;
  }
}
</style>
